// 格式化日期
/*
* @formate 'yyyy-MM-dd HH:mm:ss'
*
*/
import Vue from 'vue'
export function formateDate(time, formate) {
  const date = new Date(time)
  const arr1 = formate.split(' ')
  let fomatArray1 = []
  let fomatArray2 = []
  if (arr1[0]) {
    fomatArray1 = arr1[0].split('-')
  }
  if (arr1[1]) {
    fomatArray2 = arr1[1].split(':')
  }
  const data = {
    yyyy: date.getFullYear(),
    MM: date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1),
    dd: date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
    HH: date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
    mm: date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes(),
    ss: date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
  }
  let dateStr = ''
  for (const i in fomatArray1) {
    if (i < fomatArray1.length - 1) {
      dateStr = dateStr + data[fomatArray1[i]] + '-'
    } else {
      dateStr = dateStr + data[fomatArray1[i]]
    }
  }
  for (const i in fomatArray2) {
    if (i < fomatArray2.length - 1) {
      if (i === '0') {
        dateStr = dateStr + ' '
      }
      dateStr = dateStr + data[fomatArray2[i]] + ':'
    } else {
      dateStr = dateStr + data[fomatArray2[i]]
    }
  }
  return dateStr
}
// 返回当前日期所在第几周
export function getWeekNum(date) {
  const currentDate = new Date(date)
  const fisrtDate = new Date(currentDate.getFullYear(), 0, 1)
  const d = Math.round((currentDate.valueOf() - fisrtDate.valueOf()) / 86400000)
  const weekNum = Math.ceil((d + ((fisrtDate.getDay() + 1) - 1)) / 7)
  return weekNum
}
// 返回周几
export function getWeekDay(date) {
  const currentDate = new Date(date)
  const weekArray = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return weekArray[currentDate.getDay()]
}
// 比较日期
export function compareDate(date1, date2) {
  const time1 = new Date(date1).getTime()
  const time2 = new Date(date2).getTime()
  return time1 - time2
}
// 计算提前或推后日期
export function computeDays(currentDate, days, type) {
  const curentTime = new Date(currentDate).getTime()
  const daysTime = days * 3600 * 24 * 1000
  let resutTime = 0
  if (type === 1) {
    resutTime = curentTime + daysTime
  } else {
    resutTime = curentTime - daysTime
  }
  return formateDate(resutTime, 'Y-m-d h:mm:s')
}

// 计算两个日期相差的天数
export function subtractDays(firstDay, secondDay) {
  const aDay = 3600 * 24 * 1000
  const firstDayTime = new Date(firstDay).getTime()
  const secondDayTime = new Date(secondDay).getTime()
  return Math.ceil((secondDayTime - firstDayTime) / aDay)
}

// token 管理
export function setNewToken(tokenData, timeLen) {
  const startTime = new Date().getTime()
  const tokenInfo = {
    data: tokenData,
    endTime: startTime + timeLen || 1000 * 60 * 60 * 24 * 7
  }
  localStorage.tokenInfo = JSON.stringify(tokenInfo)
}
export function getTokenInfo() {
  if (localStorage.tokenInfo) {
    return JSON.parse(localStorage.tokenInfo).data
  } else {
    return false
  }
}

export function getUserInfo() {
  if (localStorage.userInfo) {
    return JSON.parse(localStorage.userInfo)
  } else {
    return false
  }
}
// token 管理
export function setNewIdenity(timeLogin) {
  const startTime = new Date().getTime()
  localStorage.lastTime = Number(timeLogin) + startTime
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 设置permissions
 * @param {*}
 */
export function setPermissions(permissions) {
  // store.commit('setPermissions', permissions)
  sessionStorage.setItem('permissions', JSON.stringify(permissions))
}

/**
 * 获取permissions
 * @param {*}
 */
export function hasPerm(key) {
  return JSON.parse(sessionStorage.permissions).indexOf(key) !== -1 || false
}

// Dialog Drawer 通用底部按钮添加loading事件
/*
* @footerBtnListName '[String] drawerController'
* @triggerName '[String]confirm'
* @event '[Boolean] true false'
*/
export function btnLoading(footerBtnListName, triggerName, event) {
  this[footerBtnListName].forEach(item => {
    if (item.trigger === triggerName) {
      this.$set(item, 'loading', event)
    }
  })
}

// 根据文件结构获取路由列表
// @params ignoreList 要忽略匹配的字符串构成的数组
export function getRouteChildren(ignoreList = ['children']) {
  let files = require.context('../pages', true, /.vue$/).keys()
  ignoreList.forEach(string => {
    files = files.filter(item => {
      if (item.indexOf(string) === -1) {
        return item
      }
    })
  })
  let path = JSON.parse(JSON.stringify(files))
  path = path.map(item => {
    item = item.replace(/^./, '')
    return item
  })
  files = files.map(item => {
    let pathList = item.split('/')
    pathList = pathList.map(path => {
      path = path.split('')
      if (path.length) {
        path[0] = path[0].toLowerCase()
      }
      return path.join('')
    })
    pathList = pathList.map(path => {
      return path.replace(/[A-Z]+/g, (word) => {
        return `-${word.toLowerCase()}`
      })
    })
    item = pathList.join('/')
    item = item.replace(/\/index.vue$/, '')
    item = item.replace(/.vue$/, '')
    item = item.replace(/^./, '')
    return item
  })
  const children = files.map((item, index) => {
    return {
      path: item,
      component: (resolve) => require([`@/pages${path[index]}`], resolve)
    }
  })
  return children
}

// 判断字符串 是不是JSON字符串
export function isJSON(str) {
  try {
    if (typeof JSON.parse(str) === 'object') {
      return true
    } else {
      return false
    }
  } catch (error) {
    return false
  }
}

// 深拷贝

export function deepClone(target) {
  // 定义一个变量
  let result
  // 如果当前需要深拷贝的是一个对象的话
  if (typeof target === 'object') {
    // 如果是一个数组的话
    if (Array.isArray(target)) {
      result = [] // 将result赋值为一个数组，并且执行遍历
      for (const i in target) {
        // 递归克隆数组中的每一项
        result.push(deepClone(target[i]))
      }
      // 判断如果当前的值是null的话；直接赋值为null
    } else if (target === null) {
      result = null
      // 判断如果当前的值是一个RegExp对象的话，直接赋值
    } else if (target.constructor === RegExp) {
      result = target
    } else {
      // 否则是普通对象，直接for in循环，递归赋值对象的所有值
      result = {}
      for (const i in target) {
        result[i] = deepClone(target[i])
      }
    }
  // 如果不是对象的话，就是基本数据类型，那么直接赋值
  } else {
    result = target
  }
  // 返回最终结果
  return result
}

export function formatDate(date) {
  const temp = new Date(date)
  return formateDate(temp, 'yyyy-MM-dd HH:mm:ss')
}

export function currentDate(n = 0) { // n=0(默认当前日期)
  const date = new Date()
  date.setMonth(date.getMonth() - Number(n))
  return `${date.getFullYear()}-${formatNumber(date.getMonth() + 1)}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 下载文件
 * @param res 资源
 * @param name 文件名称
 */
export function downloadFileFun(res, name) {
  const blob = new Blob([res], {
    type: `${res.type}charset=utf-8`
  })
  const downloadLink = document.createElement('a')
  const URL = window.URL || window.webkitURL || window.moxURL
  const downUrl = URL.createObjectURL(blob)
  downloadLink.href = downUrl
  downloadLink.download = name
  downloadLink.click()
  window.URL.revokeObjectURL(downUrl)
}
function handleSetForm(form, type, row) {
  for (const key in form) {
    if (type === 0) { // 清空表单
      form[key] = ''
    } else {
      if (row[key] !== '' || row[key] !== null || row[key] !== undefined) {
        form[key] = row[key]
      }
    }
  }
}
// 来源下拉框
function getDataSource() {
  return [
    {
      label: '本系统',
      value: 'this_system'
    },
    {
      label: 'HIS',
      value: 'his'
    },
    {
      label: '护理管理系统',
      value: 'nursing_management_system'
    }

  ]
}

// 数据权限下拉框
function getDataAuth() {
  return [
    {
      label: '员工',
      value: 'employee'
    },
    {
      label: '主任',
      value: 'director'
    },
    {
      label: '绩效办、院长',
      value: 'officeOrDean'
    }

  ]
}
function isNull(value) {
  if (value === '' || value === undefined || value === null) {
    return true
  } else {
    return false
  }
}

function getYearQuarter() {
  const { ccType = 1 } = localStorage.getItem('checkCycle') && JSON.parse(
    localStorage.getItem('checkCycle')
  ) || {}
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, 0) // 获取当前月份，注意月份从0开始，所以需要加1
  // const day = String(date.getDate()).padStart(2, 0)
  // 计算当前月份是第几个季度
  const nyrStart = `${year}-${month}-01`
  const nyrEnd = `${year}-${month}-${getCurrentMonthDays()}`

  const quarter = Math.floor((month - 1) / 3) + 1
  let result = `${date.getFullYear()}-${quarter}`
  if (ccType === 1) { // 月
    result = [nyrStart, nyrEnd]
  }
  return result
}

function checkCycle() {
  return localStorage.getItem('checkCycle') && JSON.parse(
    localStorage.getItem('checkCycle')
  ) || {}
}

function getCurrentMonthDays() {
  const currentDate = new Date()
  const currentMonth = currentDate.getMonth()
  const nextMonth = new Date(currentDate.getFullYear(), currentMonth + 1, 1)
  const lastDayOfMonth = new Date(nextMonth.getTime() - 1)
  const numberOfDays = lastDayOfMonth.getDate()
  return numberOfDays
}

function arraySplite(value, index) {
  return value && !Array.isArray(value) && value.split('-')[index] || ''
}
function getParam(value) { // 获取周期参数
  const type = checkCycle()?.ccType
  return {
    // 周期-季
    ccCycle: type === 0 ? arraySplite(value, 0) : undefined, // 年
    ccQuarter: type === 0 ? arraySplite(value, 1) : undefined, // 季
    // 周期-月
    ccEndDate: type === 1 ? value[1] : undefined,
    ccStartDate: type === 1 ? value[0] : undefined,
    ccType: type
  }
}
// 填充表单数据
Vue.prototype.$handleSetForm = handleSetForm
Vue.prototype.$getDataSource = getDataSource
Vue.prototype.$getDataAuth = getDataAuth
Vue.prototype.$isNull = isNull
Vue.prototype.$quarter = getYearQuarter
Vue.prototype.$arraySplite = arraySplite
Vue.prototype.$checkCycle = checkCycle
Vue.prototype.$getParam = getParam

export default {
  currentDate,
  formatNumber,
  downloadFileFun,
  setNewToken,
  getTokenInfo
}
